import { constantRoutes } from '@/router'
import permissionRoutes, { componentMap } from '@/router/permissionRoutes'
import { getMenus } from '@/api/user'

function generateRoutes(menus) {
  function createRoute(menu) {
    const route = {
      id: menu.id,
      parentId: menu.parentId || 0,
      orderNum: menu.orderNum,
      path: menu.url || '',
      hidden: menu.hidden,
      component: componentMap[menu.express || ''],
      meta: { title: menu.name, icon: menu.icon },
    }

    if (!route.path) {
      route.meta.breadcrumb = false
    }
    if (menu.express) {
      route.name = menu.express
    }

    if (menu.remark) {
      route.redirect = menu.remark
    }

    return route
  }

  function generateTree(topRoutes, parentMap) {
    if (!topRoutes || topRoutes.length === 0) {
      return
    }
    topRoutes.sort((a, b) => {
      return a.orderNum - b.orderNum
    })
    topRoutes.forEach(route => {
      route.children = parentMap[route.id]
      generateTree(route.children, parentMap)
    })
  }

  const parentMap = {}
  const topRoutes = []

  menus.forEach(menu => {
    const route = createRoute(menu);
    if (!route.parentId) {
      topRoutes.push(route)
    }

    if (parentMap[route.parentId]) {
      parentMap[route.parentId].push(route)
    } else {
      parentMap[route.parentId] = [
        route
      ]
    }
  })
  generateTree(topRoutes, parentMap)
  return topRoutes
}

const state = {
  routes: [...constantRoutes],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  getRoutes({ commit, state }, roles) {
    return new Promise((resolve, reject) => {
      // if (process.env.NODE_ENV == 'development') {
      //   let routes = [...permissionRoutes];
      //   commit('SET_ROUTES', routes);
      //   resolve(routes);
      //   return;
      // }

      getMenus().then(response => {
        const { data } = response
        const routes = generateRoutes(data)
        routes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', routes)
        resolve(state.routes);
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
